package com.simple.util;

import java.util.HashMap;
import java.util.Map;

import com.simple.datax.bo.ITbResourcesBO;
import com.simple.util.common.SpringUtil;

public final class TbResourceLoad {
    private static final String LOCK = "lock";

    private static TbResourceLoad instance = new TbResourceLoad();

    public static TbResourceLoad getInstance() {
        synchronized(LOCK){
            if(instance == null) {
                instance = new TbResourceLoad();
            }
        }

        return instance;
    }
    
    @SuppressWarnings("rawtypes")
	private Map<String,Map> getTbResourceMap(){
    	final ITbResourcesBO tbResourcesBO = (ITbResourcesBO) SpringUtil.getBean("tbResourcesBO");
    	return tbResourcesBO.getAllTbResourceMap();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map<String,String> getMap(final String[] packageAry,final String locale) {
        final Map<String,String> resourceMap = new HashMap<String,String>();
        for(int i=0;i<packageAry.length;i++){
            final Map<String, Map> pkMap =  getTbResourceMap().get(packageAry[i]);
            if(pkMap!=null){
                final Map<String,String> locMap = pkMap.get(locale);
                if(locMap!=null){
                    resourceMap.putAll(locMap);
                }
            }
        }
        return resourceMap;
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map<String,Map<String,String>> getMap(final String[] packageAry) {
        final Map<String, Map<String, String>> totalPkMap = new HashMap<String,Map<String, String>>();
        for(int i=0;i<packageAry.length;i++){
            final Map<String, Map> pkMap =  getTbResourceMap().get(packageAry[i]);
            if(pkMap!=null){
                for(String locale:pkMap.keySet()){
                    if(!totalPkMap.containsKey(locale)){
                        final Map<String, String> locMap = new HashMap<String, String>();
                        totalPkMap.put(locale, locMap);
                    }
                    totalPkMap.get(locale).putAll(pkMap.get(locale));
                }
            }
        }
        return totalPkMap;
    }
    
    @SuppressWarnings("rawtypes")
    public String getString(final String packagestr,final String locale,final String key) {
        String value = null;
        if( getTbResourceMap().containsKey(packagestr) &&  getTbResourceMap().get(packagestr).containsKey(locale) && (((Map)( getTbResourceMap().get(packagestr)).get(locale)).containsKey(key))){
            value = (String)((Map) getTbResourceMap().get(packagestr).get(locale)).get(key);
        }
        return value;
    }
    
    public Map<String,String> getMap(final String packageName,final String locale){
    	return getMap(new String[]{packageName}, locale);
    	
    }
}
